const {
  CreatesoftService,
  removesoftService,
  restoresoftService,
  findsoftService,
  updatesoftService,
} = require("../Service/software.service");
const {
  unSupportedFileType,
  removesoftError,
  restoresoftError,
  updatesoftError,
} = require("../Constant/err.type");
const path = require("path");
const fs = require("fs");
class softwareController {
  async createsoft(ctx, next) {
    const { softName, softMenuInfo, iconUrl } = ctx.request.body;
    // 使用数据库存储icon图片名字
    const res = await CreatesoftService(ctx, softName, iconUrl, softMenuInfo);
    if (res) {
      ctx.body = {
        code: 0,
        message: "创建软件成功",
        result: res,
      };
    }
  }
  async removesoft(ctx, next) {
    try {
      const res = await removesoftService(ctx.params.id);
      if (res) {
        ctx.body = {
          code: 0,
          message: "软件成功删除",
          result: "",
        };
      } else {
        return ctx.app.emit("error", removesoftError, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }
  async restoresoft(ctx, next) {
    try {
      const res = await restoresoftService(ctx.params.id);
      if (res) {
        ctx.body = {
          code: 0,
          message: "软件成功恢复",
          result: "",
        };
      } else {
        return ctx.app.emit("error", restoresoftError, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }
  async findAllsoft(ctx, next) {
    const res = await findsoftService();
    ctx.body = {
      code: 0,
      message: "获取软件信息成功",
      result: res,
    };
  }
  async updatesoft(ctx, next) {
    try {
      const id = ctx.params.id;
      const res = await updatesoftService(id, ctx.request.body);
      if (res) {
        ctx.body = {
          code: 0,
          message: "修改软件信息成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", updatesoftError, ctx);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async upload(ctx, next) {
    const { file } = ctx.request.files;
    if (!file) {
      ctx.body = "No file Upload";
      return;
    }
    const fileTypes = ["image/jpeg", "image/png", "image/jpg"];
    if (file.filepath) {
      if (!fileTypes.includes(file.mimetype)) {
        // 如果文件不符合要求 通过fs模块删除文件
        fs.unlinkSync(file.filepath);
        return ctx.app.emit("error", unSupportedFileType, ctx);
      }
      ctx.body = {
        code: 0,
        message: "软件图片上传成功",
        result: {
          iconUrl: path.basename(file.filepath),
        },
      };
    }
  }
}

module.exports = new softwareController();
